#!/bin/bash
THIS_SCRIPT_VERSION=1.0
THIS_SCRIPT_URL="http://apt.walnutpi.com//debian/wpi-update"
THIS_SCRIPT_SAVE="/tmp/wpi-update-air"

SOURCE_STR="deb [trusted=yes] http://apt.walnutpi.com//debian/ bookworm main"
TMP_SOURCE_FILE="/tmp/wpi-update-source"
LOG_URL_CN="http://apt.walnutpi.com//debian/release-cn.log"
LOG_URL_EN="http://apt.walnutpi.com//debian/release-en.log"
LOG_URL=""
RELEASE_FILE="/etc/WalnutPi-release"
FILE_LOG_SAVE="/tmp/wpi-update-update.log"
FILE_PACKAGES="/tmp/wpi-update-packages.txt"

run_as_client() {
    $@ > /dev/null 2>&1
}

run_status() {
    local message=$1
    shift
    # set +e
    start_time=$(date +%s)
    while true; do
        echo -e  -n "...\t$message"
        output=$("$@" 2>&1)
        exit_status=$?
        if [ $exit_status -ne 0 ]; then
            echo -e "\r\033[31m[error]\033[0m"
            echo -e $output
            exit 1
        else
            end_time=$(date +%s)
            duration=$((end_time - start_time))
            echo -e "\r\033[32m[ok]\033[0m\t${message}"
            break
        fi
    done
    # set -e
}
echo_red() {
    echo -e "\r\033[31m$1\033[0m"
}
echo_green() {
    echo -e "\r\033[32m$1\033[0m"
}
echo_blue() {
    echo -e "\r\033[36m$1\033[0m"
}


declare -A STR_CN
declare -A STR_EN
declare -A STR_AUTO

STR_CN['sudo_warn']="\n\t请使用sudo来运行本指令\n"
STR_EN['sudo_warn']="\n\tError:  please use sudo !\n"

STR_CN['version_newest_h']="\n\t你的系统版本已经是最新的  ,无需更新"
STR_CN['version_newest_l']="  ,无需更新\n"
STR_EN['version_newest_h']="\n\tYour system version is already up to "
STR_EN['version_newest_l']="  ,No need to update\n"

STR_CN['backup_warn']=$(cat <<- 'EOF'
\t=================================
\t||前注意备份好个人数据,以免发生意外
\t=================================
EOF
)
STR_EN['backup_warn']=$(cat <<- 'EOF'
\t========================================================
\tBe sure to back up your personal data to avoid accidents
\t========================================================
EOF
)
STR_CN['are_u_redy']="您希望继续执行吗？"
STR_EN['are_u_redy']="Do you want to continue?"

STR_CN['abort']="中止"
STR_EN['abort']="Abort"

STR_CN['install_error']="ERROR: 获取不到可更新的包"
STR_EN['install_error']="ERROR: Could not get updatable package"


if [[ $LANG ==  zh_CN* ]]; then
    LOG_URL=$LOG_URL_CN
    for key in "${!STR_CN[@]}"; do
        STR_AUTO[$key]="${STR_CN[$key]}"
    done
else
    LOG_URL=$LOG_URL_EN
    for key in "${!STR_EN[@]}"; do
        STR_AUTO[$key]="${STR_EN[$key]}"
    done
fi


if [[ $EUID -ne 0 ]]; then
    echo -e "${STR_AUTO['sudo_warn']}"
    exit 1
fi

echo $SOURCE_STR > $TMP_SOURCE_FILE
FLAG=$1

if [[ $FLAG =~ -v ]]; then
    echo $THIS_SCRIPT_VERSION
    exit 0
fi

if [[ $FLAG =~ -s ]]; then
    run_as_client  wget -c $LOG_URL -O $FILE_LOG_SAVE
    NEW_VERSION=$(grep -o '\[[^]]*\] - [^ ]*' $FILE_LOG_SAVE | head -n 1 | awk '{print $3}')
    echo "$NEW_VERSION "
    exit 0
fi

# 获取网站上存储的本脚本,进行更新
if [[ $FLAG != "no_update" ]]; then
    if [ -f $THIS_SCRIPT_SAVE ]; then
        rm $THIS_SCRIPT_SAVE
    fi
    run_status "update this script ...."  wget -c $THIS_SCRIPT_URL -O $THIS_SCRIPT_SAVE
    NEW_SCRIPT_VERSION=$(grep -o 'THIS_SCRIPT_VERSION=[0-9.]*' $THIS_SCRIPT_SAVE | cut -d '=' -f 2)
    # if [[ $* =~ -v ]]; then
    #     echo "新版本=$NEW_SCRIPT_VERSION"
    # fi

    if [[ "$NEW_SCRIPT_VERSION" > "$THIS_SCRIPT_VERSION" ]]; then
        cp $THIS_SCRIPT_SAVE $0
        exec bash $0 no_update
        
    fi
fi


# 从文件中获取版本号和日期
if [[ -f $RELEASE_FILE ]]; then
    BOARD_VER=$(grep '^version=' $RELEASE_FILE | cut -d '=' -f 2)
    BOARD_DATE=$(grep '^date=' $RELEASE_FILE | cut -d '=' -f 2)
    # echo "BOARD_VER: $BOARD_VER"
    # echo "BOARD_DATE: $BOARD_DATE"
fi

# 获取release.log
if [ -f $FILE_LOG_SAVE ]; then
    rm $FILE_LOG_SAVE
fi
run_status "download the release log ...."  wget -c $LOG_URL -O $FILE_LOG_SAVE
NEW_VERSION=$(grep -o '\[[^]]*\] - [^ ]*' $FILE_LOG_SAVE | head -n 1 | awk '{print $3}')

# 计算release.log内是否有更新的log
BOARD_DATE_SECONDS=$(date -d"$BOARD_DATE" +%s)
DATES_IN_LOG=$(grep -o '\[[^]]*\]' $FILE_LOG_SAVE | tr -d '[]')
LAST_DATE=""
HAS_NEW=""
for DATE in $DATES_IN_LOG; do
    DATE_SECONDS=$(date -d"$DATE" +%s)
    if (( DATE_SECONDS > BOARD_DATE_SECONDS )); then
        HAS_NEW="yew"
    fi
    if (( DATE_SECONDS <= BOARD_DATE_SECONDS )); then
        LAST_DATE=$DATE
        break
    fi
done

if [ -z "$HAS_NEW" ]; then
    echo -e  "${STR_AUTO['version_newest_h']}[${NEW_VERSION}]${STR_AUTO['version_newest_l']}"
    exit 0
fi

# 输出是否安装的提示语
clear
echo -e "[${BOARD_VER}] -> \033[32m[${NEW_VERSION}]\033[0m"
echo -e "${STR_AUTO['backup_warn']}"

sed -n "1,/\\[$LAST_DATE\\]/p" $FILE_LOG_SAVE | sed '/\['$LAST_DATE'\]/d'
echo -n "${STR_AUTO['are_u_redy']} "

if [[ $* =~ -y ]] || [[  $* =~ -Y ]]; then
    echo ""
else
    read -p "[Y/n]" CHOICE
    if [[ "$CHOICE" != "y" && "$CHOICE" != "Y" ]]; then
        echo -e "${STR_AUTO['abort']}."
        exit 1
    fi

fi

# 获取更新，安装
run_status "get the package info ..." apt-get update -o Dir::Etc::sourcelist="$TMP_SOURCE_FILE" -o Dir::Etc::sourceparts="-" -o APT::Get::List-Cleanup="0"
apt-get --just-print upgrade -o Dir::Etc::sourcelist="$TMP_SOURCE_FILE" -o Dir::Etc::sourceparts="-" -o APT::Get::List-Cleanup="0" | grep 'Inst' | cut -d ' ' -f 2 >  $FILE_PACKAGES
if [ ! -s $FILE_PACKAGES ]; then
    echo -e "${STR_AUTO['install_error']}."
    exit 1
fi
while read PACKAGE_NAME; do
    run_status "install $PACKAGE_NAME"  apt-get install -o Dir::Etc::sourcelist="$TMP_SOURCE_FILE" -o Dir::Etc::sourceparts="-" -o APT::Get::List-Cleanup="0" $PACKAGE_NAME
done < $FILE_PACKAGES


# 替换新版本号
sed -i "s/^version=.*/version=$NEW_VERSION/" $RELEASE_FILE

# 替换新时间
DATE=$(grep -o '\[[^]]*\]' $FILE_LOG_SAVE | head -n 1 | tr -d '[]')
sed -i "s/^date=.*/date=$DATE/" $RELEASE_FILE
